package com.tiyende.credit.loop.ui.fragment

import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Color
import android.graphics.Typeface
import android.os.Build
import android.provider.ContactsContract
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.text.style.StyleSpan
import android.text.style.TypefaceSpan
import android.view.LayoutInflater
import android.view.View
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.tiyende.credit.loop.R
import com.tiyende.credit.loop.TiyendeApp
import com.tiyende.credit.loop.common.CommonFragment
import com.tiyende.credit.loop.configs.TiyendeApiUrl.addCommonParams
import com.tiyende.credit.loop.configs.TiyendeConfigs
import com.tiyende.credit.loop.databinding.TiyendeFragmentAuthenticationStepContactBinding
import com.tiyende.credit.loop.event.TiyendeEventPointType
import com.tiyende.credit.loop.ui.activity.TiyendeAuthenticationStepsActivity
import com.tiyende.credit.loop.ui.adapter.TiyendeAuthenticationStepContactAdapter
import com.tiyende.credit.loop.utils.TiyendeStringDeepCopy
import com.tiyende.credit.loop.utils.log.TiyendeLogger
import com.tiyende.credit.loop.utils.track.TrackPointManager
import org.json.JSONArray
import org.json.JSONObject
import java.util.regex.Pattern

/**
 * TiyendeCredit
 * @Author wwdeng
 * @CreateTime: 2024/11/19 10:38
 * @Annotation：认证流程 - 联系人
 */
class TiyendeAuthenticationStepContactFragment(): CommonFragment() {
//    lateinit var binding: TiyendeFragmentAuthenticationStepContactBinding
    private var _binding: TiyendeFragmentAuthenticationStepContactBinding? = null
    private val binding get() = _binding ?: throw IllegalStateException(
        "Cannot access binding because it is null. Either the view hasn't been created yet, or it has already been destroyed."
    )

    private var contactAdapter: TiyendeAuthenticationStepContactAdapter? = null
    private var tiyendeCacheContactItem = ""

    private var authenticationStepAct: TiyendeAuthenticationStepsActivity? = null
    private var stepItem: JSONObject? = null
    private var stepTitle = ""
    constructor(act: TiyendeAuthenticationStepsActivity, stepItem: JSONObject): this(){
        this.authenticationStepAct = act
        this.stepItem = stepItem
    }

    override fun getTiyendeRootView(inflater: LayoutInflater): View {
        _binding = TiyendeFragmentAuthenticationStepContactBinding.inflate(inflater)
        return binding.root
    }

    override fun initTiyendeView() {
        initTiyendeAuthenticationStepContactRecyclerView()
        stepItem?.let {
            val showKey = getString(R.string.tiyende_authentication_step_contact_info_tips_key)
            val showText = String.format(getString(R.string.tiyende_authentication_step_contact_info_tips),showKey)
            val startIndex = showText.indexOf(showKey)
            val dataSecuritySpannable = SpannableString(showText)
            dataSecuritySpannable.setSpan(ForegroundColorSpan(Color.parseColor("#FF3ED9AB")), startIndex, startIndex + showKey.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { // TypefaceSpan(Typeface) added in API 28
                dataSecuritySpannable.setSpan(TypefaceSpan(TiyendeApp.app.getBoldTypeface()), startIndex, startIndex + showKey.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
            } else {
                dataSecuritySpannable.setSpan(StyleSpan(Typeface.BOLD), startIndex, startIndex + showKey.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
            }
            _binding?.textAuthStepContactInfoTips?.text = dataSecuritySpannable
        }
    }

    override fun initTiyendeListener() {
        //添加
        _binding?.btnContactAdd?.setOnClickListener {
            if (tiyendeCacheContactItem.isNotEmpty()){
                contactAdapter?.addLastItem(JSONObject(tiyendeCacheContactItem))
                contactAdapter?.notifyDataSetChangedWrapper()
            }

            contactAdapter?.let {
                //最多添加50个联系人
                _binding?.btnContactAdd?.isEnabled = it.itemCount < 50
            }
        }

        //提交
        _binding?.btnContactNext?.setOnClickListener {
            _binding?.root?.clearFocus()
            addEventPointRequestAction(String.format(TiyendeEventPointType.CLICK.TIYENDE_CLICK_STEP_XX_NEXT, stepTitle),"")
            if (!isAllowContactSubmit() || stepItem == null){
                showErrorTipsDialog(getString(R.string.tiyende_dialog_tips_submit_error), stepTitle)
                return@setOnClickListener
            }
            stepItem?.let {
                val params = JSONObject().addCommonParams().apply {
                    put("path",it.optString("apiUrl").replace("/",""))
                }

                //拼接上传数据格式
                contactAdapter?.let { adapter ->
                    val paramArray = JSONArray()
                    for (i in 0..< adapter.itemCount){
                        val obj = JSONObject()
                        val dataArray = adapter.getItem(i).optJSONArray("dataList")
                        dataArray?.let {
                            for (j in 0..< it.length()){
                                val item = it.optJSONObject(j)
                                val paramName = item.optString("paramName")
                                val selectItem = item.optJSONObject("selectItem")
                                var paramValue = selectItem?.optString("value")
                                if (paramName == "relation" && paramValue == item.optString("relationOtherKey")){
                                    paramValue = selectItem?.optString("otherValue")
                                    //如果关系为“Other”，输入的内容为纯数字，则直接传“Other”
                                    if (isTiyendeRelationOtherAllNumber(paramValue)){
                                        paramValue = item.optString("relationOtherKey")
                                    }
                                }
                                obj.put(paramName,paramValue)
                            }
                        }
                        paramArray.put(obj)
                    }
                    params.put(it.optString("contactParamName"),paramArray)

                    // TODO: Step Next 批量埋点上报
                    TrackPointManager.getInstance().manualReport()

                    authenticationStepAct?.onAuthenticationStepSubmitAction(params)
                }
            }
        }
    }

    override fun loadTiyendeData() {
        //联系人关系关键字
        val contactRelationOther = getString(R.string.tiyende_authentication_step_contact_info_relation_other)
        val contactRelationOtherHint = getString(R.string.tiyende_authentication_step_contact_info_relation_other_hint)
        //是否支持通讯录选择联系人
        val isContactPick = isTiyendeContactPick()
        val dataList = arrayListOf<JSONObject>()
        stepItem?.let {
            stepTitle = it.optString("stepTitle")
            // TODO: 这里dataList需要深拷贝，否则列表会共用一个数据源
            val stringCopy = TiyendeStringDeepCopy(it.optString("dataList"))
            for (i in 0..<it.optInt("itemCount")){
                val obj = JSONObject()
                val dataArray = JSONArray(stringCopy.content)
                for (j in 0..<dataArray.length()){
                    val dataObj = dataArray.optJSONObject(j)
                    dataObj.put("isContactPick",isContactPick)
                    dataObj.put("title",dataObj.optString("title"))
                    when(dataObj.optString("action")){
                        "CONTACT_GROUP_RELATION",
                        "SELECT",
                        -> {
                            dataObj.put("action","CONTACT_GROUP_RELATION")
                            var relationShips = it.optJSONArray("relationShips")
                            if (TiyendeConfigs.isSwahili()){
                                relationShips = it.optJSONArray("relationShips_sw")
                            }
                            val valueArray = relationShips?.optJSONArray(i)
                            val values = JSONArray()
                            valueArray?.let { relationArray ->
                                if (!relationArray.toString().contains(contactRelationOther)){
                                    //手动添加一条Other
                                    relationArray.put(contactRelationOther)
                                }
                                for (n in 0..<relationArray.length()) {
                                    val value = JSONObject()
                                    value.put("title", relationArray.optString(n))
                                    if (TiyendeConfigs.isSwahili()){
                                        value.put("title_sw", relationArray.optString(n))
                                    }
                                    value.put("value", relationArray.optString(n))
                                    values.put(value)
                                }
                            }
                            dataObj.put("values", values)
                            dataObj.put("relationOtherKey",contactRelationOther)
                            dataObj.put("relationOtherHint",contactRelationOtherHint)
                        }
                        "CONTACT_GROUP_PHONE" -> {//联系人电话
                            dataObj.put("action","CONTACT_GROUP_PHONE")
                        }
                        "CONTACT_GROUP_NAME" -> {//联系人姓名
                            dataObj.put("action","CONTACT_GROUP_PHONE")
                        }
                        else -> {
                            dataObj.put("action","INPUT")
                        }
                    }
                }
                obj.put("stepTitle",stepTitle)
                obj.put("dataList",dataArray)
                dataList.add(obj)
            }
        }
        contactAdapter?.data = dataList
        contactAdapter?.let {
            if (it.itemCount > 0){
                //缓存最后一个联系人item数据，用户新增item
                tiyendeCacheContactItem = TiyendeStringDeepCopy(it.lastItem.toString()).content
            }
        }
        //联系人启动埋点，防止多次上报
        addEventPointRequestAction(TiyendeEventPointType.PAGE.TIYENDE_PAGE_STEP_CONTACT_START)
    }

    /**
     * 初始化Views
     */
    private fun initTiyendeAuthenticationStepContactRecyclerView(){
        //        _binding?.recyclerViewContact.setHasFixedSize(true)
        _binding?.recyclerViewContact?.isNestedScrollingEnabled = false
        _binding?.recyclerViewContact?.isFocusableInTouchMode = false //不需要焦点
        val layoutManager = LinearLayoutManager(context)
        layoutManager.orientation = RecyclerView.VERTICAL
        _binding?.recyclerViewContact?.layoutManager = layoutManager
//        val topDecoration = AppDensityUtil.dp2px(14f)
//        _binding?.recyclerView.addItemDecoration(LinearSpacingItemDecoration(0,0,0,topDecoration))
        contactAdapter = TiyendeAuthenticationStepContactAdapter(binding.root,_binding?.recyclerViewContact)
        _binding?.recyclerViewContact?.adapter = contactAdapter
        _binding?.recyclerViewContact?.itemAnimator = DefaultItemAnimator()
        contactAdapter?.setOnChildItemSelectMobileListener(object : TiyendeAuthenticationStepContactAdapter.IChildItemSelectMobileListener{
            override fun onChildSelectMobileClick(parentPosition: Int, childModel: JSONObject) {
                val startTime = System.currentTimeMillis()
                authenticationStepAct?.pickContact?.startPickContact { contactName, contactMobile ->
                    TiyendeLogger.e(">>>>>>>>>>>>>>>>>>>>>$contactName>>>>>>>$contactMobile")
                    val subTimestamp = System.currentTimeMillis() - startTime
                    val parentItem = contactAdapter?.getItem(parentPosition)

                    parentItem?.let {
                        //设置联系人名称
                        val dataArray = it.optJSONArray("dataList")
                        if (dataArray != null) {
                            for (i in 0..<dataArray.length()) {
                                val itemObj = dataArray.optJSONObject(i)
                                if (itemObj.optString("paramName") == "fullName"){
                                    val obj = JSONObject()
                                    obj.put("title",contactName)
                                    obj.put("value",contactName)
                                    itemObj.put("selectItem",obj)
                                    val subRemark = "${contactName}$$${subTimestamp}"
                                    addEventPointRequestAction(String.format(TiyendeEventPointType.CLICK.TIYENDE_CLICK_STEP_XX_SELECT, "${it.optString("stepTitle")}_${itemObj.optString("paramName")}_${parentPosition+1}"), subRemark)
                                    continue
                                }
                                if (itemObj.optString("paramName") == "mobile"){
                                    val obj = JSONObject()
                                    obj.put("title",contactMobile)
                                    obj.put("value",contactMobile)
                                    itemObj.put("selectItem",obj)
                                    val subRemark = "${contactMobile}$$${subTimestamp}"
                                    addEventPointRequestAction(String.format(TiyendeEventPointType.CLICK.TIYENDE_CLICK_STEP_XX_SELECT, "${it.optString("stepTitle")}_${itemObj.optString("paramName")}_${parentPosition+1}"), subRemark)
                                    continue
                                }
                            }
                        }
                    }
//                    val obj = JSONObject()
//                    obj.put("title",contactMobile)
//                    obj.put("value",contactMobile)
//                    childModel.put("selectItem", obj)
                    contactAdapter?.notifyItemChanged(parentPosition)
                }
            }
        })
    }

    /**
     * 检查是否填写完整
     * 当且仅当 isMust=”NO“为非必填
     */
    private fun isAllowContactSubmit(): Boolean{
        val dataList = arrayListOf<JSONObject>()
        contactAdapter?.let {
            for (i in 0..<it.itemCount){
                val dataArray = it.getItem(i).optJSONArray("dataList")
                if (dataArray != null){
                    for (j in 0..<dataArray.length()){
                        val item = dataArray.optJSONObject(j)
                        dataList.add(item)
                    }
                }
            }
        }
        //是否允许提交
        var isAllow = true
        for (i in 0..<dataList.size){
            val item = dataList[i]
            //存在 isMust && isMust == ”NO“  非必填
            if (item.has("isMust") && item.optString("isMust") == "NO"){
                continue
            }
            //必填 && 没有内容 || 内容为空
            if (!item.has("selectItem")){
                isAllow = false
                break
            }
            val selectItem = item.optJSONObject("selectItem")
            if (selectItem == null){
                isAllow = false
                break
            }
            val paramName = item.optString("paramName")
            val paramValue = selectItem.optString("value")
            if (paramValue.isEmpty()){
                isAllow = false
                break
            }
            if (paramName == "relation" && paramValue == item.optString("relationOtherKey") && selectItem.optString("otherValue","").isEmpty()){
                isAllow = false
                break
            }
        }
        return isAllow
    }

    /**
     * 是否支持通讯录选择
     */
    private fun isTiyendeContactPick(): Boolean{
        val intentContact = Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI)
        val resolveInfoCType = getAct().packageManager.resolveActivity(intentContact, PackageManager.MATCH_DEFAULT_ONLY)
        return resolveInfoCType != null
    }

    /**
     * 是否全为数字
     */
    private fun isTiyendeRelationOtherAllNumber(text: String?): Boolean {
        if (text.isNullOrEmpty()){
            return false
        }
        val formatLct = "^-?\\d+\\.?\\d*$"
        val patternLct = Pattern.compile(formatLct)
        return patternLct.matcher(text.trim()).matches()
    }

    override fun onDestroy() {
        super.onDestroy()
        addEventPointRequestAction(TiyendeEventPointType.PAGE.TIYENDE_PAGE_STEP_CONTACT_END)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}